package com.habdqn.easybuy.web.manage.product;

import com.habdqn.easybuy.entity.Product;
import com.habdqn.easybuy.entity.ProductCategory;
import com.habdqn.easybuy.service.ProductService;
import com.habdqn.easybuy.service.impl.ProductCategoryServiceImpl;
import com.habdqn.easybuy.service.impl.ProductServiceImpl;
import com.habdqn.easybuy.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Xing.Jiejian
 * @date 2020/11/28 0028
 */
@WebServlet(name = "ProductUpdateServlet", urlPatterns = "/manage/product/update")
@MultipartConfig
public class UpdateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String strId = request.getParameter("id");
        if (StringUtils.isNotBlank(strId)) {
            int id = Integer.parseInt(strId);
            // 先获取原用户信息
            ProductService productService = new ProductServiceImpl();
            Product product = productService.queryById(id);
            // 更新表单数据
            // 接收普通属性
            product.setName(request.getParameter("name"));
            String strCategoryId = request.getParameter("categoryId");
            if (StringUtils.isNotBlank(strCategoryId)){
                product.setCategoryId(Integer.parseInt(strCategoryId));
            }
            String strPrice = request.getParameter("price");
            if (StringUtils.isNotBlank(strPrice)){
                product.setPrice(Double.parseDouble(strPrice));
            }
            product.setDescription(request.getParameter("description"));
            String strStock = request.getParameter("stock");
            if (StringUtils.isNotBlank(strStock)){
                product.setStock(Integer.parseInt(strStock));
            }

            // 处理图片上传部分
            // 接收文件对象
            Part part = request.getPart("fileName");
            if (part!=null){
                // 获取源文件名
                String cd = part.getHeader("Content-Disposition");
                // 获取原文件名 xxx.jpg
                String filename = cd.substring(cd.lastIndexOf("=") + 2, cd.length() - 1);
                if (filename.length() > 0) {
                    // 获取原本文件的后缀
                    String extName = filename.substring(filename.lastIndexOf("."));
                    // 生成新的文件名
                    String uuid = UUID.randomUUID().toString().replace("-", "");
                    String newFilename = uuid + extName;
                    // 设定文件保存的路径(”/upload“),获取上传目录在服务器中的完整路径
                    String savePath = request.getServletContext().getRealPath("/upload/product");
                    // 将文件使用新文件名保存到服务器指定路径
                    part.write(savePath + "/" + newFilename);
                    product.setFileName("/upload/product"+newFilename);
                }
            }

            // 执行更新业务
            if (productService.update(product) != null) {
                response.setContentType("text/html;charset=utf-8");
                PrintWriter out = response.getWriter();
                out.println("<script>");
                out.println("alert('修改商品成功！');");
                out.println("location.href='" + request.getContextPath() + "/manage/product';");
                out.println("</script>");
            } else {
                request.setAttribute("errorMsg", "修改失败");
                request.setAttribute("product", product);
                request.getRequestDispatcher("/WEB-INF/manage/product/product-modify.jsp").forward(request, response);
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String strId = request.getParameter("id");
        if (StringUtils.isNotBlank(strId)) {
            int id = Integer.parseInt(strId);
            // 先获取原用户信息
            Product product = new ProductServiceImpl().queryById(id);
            // 获取所有分类
            List<ProductCategory> categories = new ProductCategoryServiceImpl().queryAll();
            request.setAttribute("product", product);
            request.setAttribute("categories",categories);
            request.getRequestDispatcher("/WEB-INF/manage/product/product-modify.jsp").forward(request, response);
        } else {
            // 未传入id则直接进入列表页
            response.sendRedirect(request.getContextPath() + "/manage/product");
        }
    }
}
